package br.com.galante.webapp.security;

import java.io.Serializable;
import java.security.Principal;

import javax.enterprise.context.RequestScoped;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.inject.Named;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;

@Named
@RequestScoped
public class Authenticator implements Serializable {
 
	private static final long serialVersionUID = -488060183004621259L;
	
	public final static String ADMIN_ROLE = "admin_role";
	public final static String USER_ROLE = "user_role";
	
	private String username;
	private String password;
 
	public void login(ActionEvent actionEvent){
		authenticate();
	}
	
        /**
         * Performs authentication via HttpServletRequest API
         */
	public boolean authenticate() {
		if (!isAuthenticated()) {
			try {
				
				getRequest().login(username, password);
				
				System.out.println("admin_role? "+isUserInRole(ADMIN_ROLE));
				System.out.println("user_role? "+isUserInRole(USER_ROLE));
				
			} catch (ServletException e) {
				FacesContext.getCurrentInstance().addMessage(null,
						new FacesMessage(FacesMessage.SEVERITY_ERROR, "Usuario e/ou senha inválido", null));
			}
		}
		return isAuthenticated();
	}
	
	public void preLogout(ActionEvent actionEvent){
		try {
			logout();
		} catch (ServletException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();			
		}
	}
 
        /**
         * Logs out using HttpServletRequest API
         */
	private void logout() throws ServletException {
		if (isAuthenticated())
			getRequest().logout();
	}
 
	public boolean isAuthenticated() {
		return getRequest().getUserPrincipal() != null;
	}
 
	public boolean isUserInRole(String role) {
		return getRequest().isUserInRole(role);
	}
 
	public Principal getPrincipal() {
		return getRequest().getUserPrincipal();
	}
 
	private HttpServletRequest getRequest() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		ExternalContext externalContext = facesContext.
                         getExternalContext();
		Object request = externalContext.getRequest();
		return request instanceof HttpServletRequest ? 
                        (HttpServletRequest) request : null;
	}
 
	public String getUsername() {
		return username;
	}
 
	public void setUsername(String username) {
		this.username = username;
	}
 
	public String getPassword() {
		return password;
	}
 
	public void setPassword(String password) {
		this.password = password;
	}
 
	public boolean isAdmin(){
		
		return isUserInRole(ADMIN_ROLE);
	}
	
	public boolean isUser(){
		
		return isUserInRole(USER_ROLE);
	}
}
